package com.diamond.web.service.system;

import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import org.springframework.stereotype.Service;

import com.diamond.core.util.ApplicationUtils;
import com.diamond.web.exceptions.AppException;
import com.diamond.web.model.system.Role;
import com.diamond.web.model.system.User;
import com.diamond.web.service.GenericService;

@Service
public class UserService extends GenericService<User,Long> {
	
	public User selectByUsername(String username) {
		String hql = "From User where username=?";
		return findForObject(hql, username);
	}

	public User authentication(User user) {
		User u = selectByUsername(user.getUsername());
		if(user.getPassword().equals(u.getPassword())){
			return u;
		}
		return null;
	}

	public void register(User model) throws AppException {
		User u = selectByUsername(model.getUsername());
		if(u==null){
			model.setCreateTime(new Date());
			model.setPassword(ApplicationUtils.pwd(model.getPassword()));
			super.insert(model);
		}else{
			throw new AppException(AppException.USER_EXIST);
		}
	}
	

	public void modify(User model, Long[] roleIds) throws ReflectiveOperationException {
		User user = selectById(model.getId());
		if(model.getPassword()!=null){
			user.setPassword(ApplicationUtils.pwd(model.getPassword()));
		}
		List<Role> roles = ApplicationUtils.FieldsToObject(Arrays.asList(roleIds), "setId", Role.class);
		user.setRoles(new HashSet<Role>(roles));
		
	}
}
